#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 10/12/2023 下午9:57
# Author: name
# File: server_api.py
# ide: PyCharm
# description:
import json
from datetime import datetime
from typing import List, Union

from fastapi import APIRouter, HTTPException, Query

from backend.app.models.server_model import ServerModel, ServerOut, ServerIn, ServerPage
from backend.app.utils.response_tepmlate import ResponseCode

server_router = APIRouter(prefix="/server", tags=["服务器管理"])


# 定义 API 路由
@server_router.post("/add")
async def create_server(server: ServerIn):
    select_server = await ServerModel.filter(name=server.name).first()
    if select_server:
        return ResponseCode(server.name).response_409()
    else:
        new_server = await ServerModel.create(
            name=server.name,
            address=server.address,
            port=server.port,
            username=server.username,
            password=server.password,
            created_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            updated_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        )
        return ResponseCode(new_server.name).response_add()


# 获取内置列表（分页查询）
@server_router.get("/page", response_model=ServerPage)
async def get_server_page_list(
        page: int = Query(1, ge=1),
        size: int = Query(10, ge=1, le=100),
        name: str = Query(None, min_length=0)
):
    skip = (page - 1) * size
    query = ServerModel.all()
    if name:
        query = query.filter(name__icontains=name)
    total = await query.count()
    servers = await query.offset(skip).limit(size).values()
    print(total)
    return ServerPage(total=total, page_size=size, current_page=page, search_key=name,results=servers)


@server_router.get("/list", response_model=List[ServerOut])
async def read_server_list():
    return await ServerModel.all()


@server_router.get("/{server_id}", response_model=ServerOut)
async def get_server(server_id: int):
    server = await ServerModel.filter(id=server_id).first()
    if not server:
        return ResponseCode(server_id).response_404()
    return server


@server_router.put("/{server_id}")
async def update_server(server_id: int, server: ServerIn):
    select_server = await ServerModel.filter(id=server_id).first()
    select_other_server = await ServerModel.exclude(id=server_id).first()
    if server.name == select_other_server.name:
        return ResponseCode(server.name).response_exist()
    if not select_server:
        return ResponseCode(server.name).response_404()
    await ServerModel.filter(id=server_id).update(
        name=server.name,
        address=server.address,
        port=server.port,
        username=server.username,
        password=server.password,
        updated_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    )
    updated_server = await ServerModel.filter(id=server_id).first()
    if not updated_server:
        return ResponseCode(server.name).response_404()
    return ResponseCode(f'服务器:{server.name}').response_update_success()


@server_router.delete("/{server_id}")
async def delete_server(server_id: int):
    deleted_count = await ServerModel.filter(id=server_id).delete()
    if not deleted_count:
        return ResponseCode(server_id).response_404()
    return ResponseCode(f"{server_id}的服务器").response_delete()
